<template>
  <view class="index-container">
    <!-- 订单状态标签 -->
    <view class="status-tabs">
      <text
        v-for="(tab, index) in tabs"
        :key="index"
        :class="{ active: activeTab == index }"
        @click="handleTabChange(index)"
      >
        {{ tab.label }}
      </text>
    </view>
    <!-- 订单列表 -->
    <scroll-view
      enable-back-to-top
      scroll-y
      class="orders-container"
      :refresher-enabled="true"
      :refresher-triggered="isTriggered"
      @refresherrefresh="onRefresherrefresh"
      @scrolltolower="loadMoreOrders"
    >
      <view class="orders">
        <!-- 没有订单时显示空状态 -->
        <view v-if="!loading && orders.length == 0" class="no-orders">
          <HyNull />
        </view>

        <!-- 订单项 -->
        <view v-for="order in orders" :key="order.id" class="order-item">
          <view class="order-header">
            <text class="order_sn">订单编号：{{ order.order_sn }}</text>
            <text class="status">
              {{ order.order_status_text }}
            </text>
          </view>

          <!-- 订单商品 -->
          <view
            v-for="item in order.items"
            :key="item.id"
            class="order-content"
          >
            <image :src="item.image" class="order-image" mode="aspectFill" />
            <view class="order-details">
              <text class="product-name">{{ item.name }}</text>
              <!-- <text class="product-num">×{{ item.num }}</text> -->
            </view>
          </view>

          <!-- 订单操作按钮 -->
          <view class="order-footer">
            <button
              v-if="showCancelButton(order.order_status)"
              class="action-button cancel"
              @click="handleCancelOrder(order.id)"
            >
              取消
            </button>
            <button
              v-if="showReceiveButton(order.order_status)"
              class="action-button receive"
              @click="handleReceiveOrder(order.id)"
            >
              收货
            </button>
            <button
              class="action-button detail"
              @click="goToOrderDetail(order.id)"
            >
              详情
            </button>
          </view>
        </view>

        <!-- 加载状态 -->
        <!-- 在订单列表底部添加加载状态 -->
        <view v-if="loading" class="loading">
          <text>加载中...</text>
        </view>

        <!-- 当没有更多数据时显示 -->
        <view v-else-if="!hasMore && orders.length > 0" class="no-more">
          <text>没有更多数据了</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref } from "vue";
import HyNull from "@/components/HyNull.vue";
import { orderListApi,cancelOrderApi } from "@/api/order";
import { showSuccess, showError,showModal } from "@/utils/feedback";
import { onShow } from "@dcloudio/uni-app";

// 订单状态常量
const ORDER_STATUS = {
  PENDING_PAYMENT: "0", // 待支付
  PENDING_SHIPMENT: "1", // 待发货
  SHIPPED: "2", // 已发货/运送中
  PENDING_RECEIPT: "3", // 待收货
  COMPLETED: "4", // 已完成
  CANCELLED: "-4", // 已取消
};

// 状态标签
const tabs = [
  { label: "全部", status: null },
  { label: "待发货", status: ORDER_STATUS.PENDING_SHIPMENT },
  { label: "待收货", status: ORDER_STATUS.PENDING_RECEIPT },
  { label: "已完成", status: ORDER_STATUS.COMPLETED },
];

const orders = ref([]);          // 订单列表
const loading = ref(false);      // 是否正在加载
const hasMore = ref(true);       // 是否还有更多数据
const isTriggered = ref(false);  // 下拉刷新触发状态
const currentPage = ref(1);      // 当前页码
const pageSize = ref(10);        // 每页数量
let debounceTimer = null;        // 防抖计时器
const activeTab = ref('');

/**
 * 获取订单列表
 * @param {Object} params - 请求参数
 */
const getOrderList = async (params = {}) => {
  const pageNum = params.pageNum || 1;

  if (pageNum == 1) {
    orders.value = [];
    hasMore.value = true;
  }
  loading.value = true;
  try {
    const res = await orderListApi({
      ...params,
      status: activeTab.value,
      pageNum,
      pageSize: pageSize.value,
    });
    if (res.code == 200) {
      orders.value = [...orders.value, ...res.data.list];
      hasMore.value = res.data.list.length >= pageSize.value;
      currentPage.value = pageNum;
    } else {
      showError(res.message);
    }
  } catch (error) {
    console.error("获取订单列表失败:", error);
    showError("获取订单列表失败，请稍后重试");
  } finally {
    loading.value = false;
    isTriggered.value = false;
  }
};

// 下拉刷新事件
const onRefresherrefresh = () => {
  isTriggered.value = true;
  getOrderList({ pageNum: 1, pageSize: pageSize.value });
};
//上拉加载更多事件（带防抖）
const loadMoreOrders = () => {
  if (!loading.value && hasMore.value) {
    if (debounceTimer) clearTimeout(debounceTimer);
    debounceTimer = setTimeout(() => {
      getOrderList({pageNum : currentPage.value + 1});
    }, 300);
  }
};

/**
 * 处理标签切换
 * @param {number} index - 标签索引
 */
const handleTabChange = (index) => {
  activeTab.value = index;
  getOrderList({ status: index });
};

/**
 * 是否显示取消按钮
 * @param {string} status - 订单状态
 * @returns {boolean}
 */
const showCancelButton = (status) => {
  return (
    status == ORDER_STATUS.PENDING_PAYMENT ||
    status == ORDER_STATUS.PENDING_SHIPMENT
  );
};

/**
 * 是否显示收货按钮
 * @param {string} status - 订单状态
 * @returns {boolean}
 */
const showReceiveButton = (status) => {
  return status == ORDER_STATUS.PENDING_RECEIPT;
};

/**
 * 处理取消订单
 * @param {string} id - 订单ID
 */
const handleCancelOrder = async(id) => {
  // 弹框提示
  const confirmed = await showModal('确认', '确定要取消该订单吗？');
  if(confirmed){
    try {
        const res = await cancelOrderApi({id});
        if (res.code == 200) {
          showSuccess("订单取消成功");
          // 刷新订单列表
          getOrderList()
        } else {
          showError(res.message);
        }
      } catch (error) {
        showError("取消订单失败，请重试");
        console.error("取消订单失败：", error);
      }
  }
  
};

/**
 * 处理确认收货
 * @param {string} id - 订单ID
 */
const handleReceiveOrder = async (id) => {
  const confirmed = await showModal('确认', '确定要收货吗？');
  if (confirmed) {
    try {
        const res = await confirmOrderApi({ id });
        if (res.code == 200) {
          showSuccess('收货成功');
          getOrderList();
        } else {
          showError(res.message);
        }
    } catch (error) {
      console.error('确认收货失败:', error);
      showToast('确认收货失败');
    }
  }
};

/**
 * 跳转到订单详情
 * @param {string} orderId - 订单ID
 */
const goToOrderDetail = (orderId) => {
  uni.navigateTo({
    url: `/pages/order/detail?id=${orderId}`,
  });
};

// 初始化加载数据
onShow(() => {
  getOrderList();
});
</script>

<style scoped lang="scss">
.index-container {
  display: flex;
  flex-direction: column;
  padding-bottom: 20px;

  // 状态标签样式
  .status-tabs {
    display: flex;
    justify-content: space-around;
    padding: 10px 0;
    margin-bottom: 10px;
    background-color: #ffffff;
    position: sticky;
    top: 0;
    z-index: 10;

    text {
      padding: 8px 12px;
      font-size: 14px;
      color: #666;

      &.active {
        color: #409eff;
        font-weight: bold;
        border-bottom: 2px solid #409eff;
      }
    }
  }

  .orders-container {
    flex: 1;
    overflow-y: auto;
    overflow-x: hidden;
  }
  // 订单列表样式
  .orders {
    padding: 0 10px;
    display: flex;
    flex-direction: column;
    gap: 15px;

    .loading,
    .no-orders,
    .no-more {
      text-align: center;
      padding: 20px;
      color: #999;
    }

    // 单个订单项样式
    .order-item {
      background-color: #fff;
      padding: 15px;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

      .order-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;
        padding-bottom: 10px;
        border-bottom: 1px solid #f5f5f5;

        .order_sn {
          font-size: 14px;
          color: #666;
        }

        .status {
          font-size: 13px;
          color: rgb(245, 28, 28);
        }
      }

      // 订单内容样式
      .order-content {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 10px;

        .order-image {
          width: 80px;
          height: 80px;
          border-radius: 4px;
          background-color: #f5f5f5;
        }

        .order-details {
          flex: 1;
          display: flex;
          flex-direction: column;

          .product-name {
            font-size: 15px;
            margin-bottom: 6px;
            color: #333;
          }

          .product-price {
            font-size: 14px;
            color: #f56c6c;
            margin-bottom: 4px;
          }

          .product-num {
            font-size: 12px;
            color: #999;
          }
        }
      }

      // 订单底部操作按钮
      .order-footer {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        gap: 10px;
        padding-top: 10px;
        border-top: 1px solid #f5f5f5;

        .action-button {
          margin: 0;
          padding: 5px 12px;
          font-size: 13px;
          border-radius: 10px;
          border: 1px solid #ddd;
          background-color: transparent;

          &.detail {
            color: #666;
            border-color: #ddd;
          }

          &.cancel {
            color: #666;
            border-color: #ddd;
          }

          &.receive {
            color: #f37b1d;
            border-color: #f37b1d;
          }
        }
      }
    }
  }
}
</style>
